<template>
  <div class="chat-container">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>聊天记录</h3>
        <el-button type="primary" size="small" @click="createNewChat">
          <el-icon><Plus /></el-icon> 新对话
        </el-button>
      </div>

      <div class="chat-list">
        <div
          v-for="chat in chatList"
          :key="chat.id"
          :class="['chat-item', { active: currentChatId === chat.id }]"
          @click="switchChat(chat.id)"
        >
          <el-avatar :size="40" :src="assistantAvatar" />
          <div class="chat-info">
            <div class="chat-title">对话 {{ chat.id }}</div>
            <div class="chat-preview">{{ chat.lastMessage || "新的对话" }}</div>
          </div>
          <div class="chat-time">{{ formatTime(chat.updateTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天主界面 -->
    <div class="chat-main">
      <div class="chat-messages" ref="messagesRef">
        <template v-for="(message, index) in messages" :key="index">
          <div :class="['message', message.role]">
            <div class="message-content">
              <div class="avatar">
                <el-avatar
                  :size="40"
                  :src="message.role === 'user' ? userAvatar : assistantAvatar"
                />
              </div>
              <div class="content">
                <div class="text">{{ message.content }}</div>
                <div class="time">{{ formatTime(new Date()) }}</div>
              </div>
            </div>
          </div>
        </template>

        <!-- 等待动画 -->
        <div v-if="loading" class="message assistant">
          <div class="message-content">
            <div class="avatar">
              <el-avatar :size="40" :src="assistantAvatar" />
            </div>
            <div class="text typing-animation">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您想咨询的农业相关问题..."
          @keydown.enter.prevent="handleEnter"
        />
        <el-button type="primary" @click="handleSend" :loading="loading">
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

interface ChatSession {
  id: string;
  lastMessage: string;
  updateTime: Date;
  messages: ChatMessage[];
}

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
  time?: Date;
}

const chatList = ref<ChatSession[]>([]);
const currentChatId = ref<string>("");
const messages = ref<ChatMessage[]>([]);
const inputMessage = ref("");
const loading = ref(false);
const messagesRef = ref<HTMLElement | null>(null);
const userAvatar = ref("");
const assistantAvatar = ref("/images/ai-avatar.jpg");

// 格式化时间
const formatTime = (date: Date) => {
  return dayjs(date).format("HH:mm");
};

// 生成会话ID
const generateChatId = (): string => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};

// 获取历史会话列表
const fetchChatHistory = async () => {
  try {
    const res = await request({
      url: "/ai/history",
      method: "get",
    });
    if (res.success && res.data) {
      const historySessions = res.data.map((chatId: string) => ({
        id: chatId,
        lastMessage: "历史会话",
        updateTime: new Date(),
        messages: [],
      }));

      chatList.value = historySessions;

      if (historySessions.length > 0) {
        switchChat(historySessions[0].id);
      }
    }
  } catch (error) {
    console.error("获取历史会话失败:", error);
    ElMessage.error("获取历史会话失败");
  }
};

// 获取指定会话的历史消息
const fetchChatHistoryById = async (chatId: string) => {
  try {
    const res = await request({
      url: `/ai/history/${chatId}`,
      method: "get",
    });
    if (res.success && res.data) {
      return res.data.map((msg: ChatMessage) => ({
        ...msg,
        time: new Date(),
      }));
    }
    return [];
  } catch (error) {
    console.error("获取历史消息失败:", error);
    ElMessage.error("获取历史消息失败");
    return [];
  }
};

// 创建新会话
const createNewChat = () => {
  const newChatId = generateChatId();
  const newChat = {
    id: newChatId,
    lastMessage: "新的对话",
    updateTime: new Date(),
    messages: [],
  };

  chatList.value.unshift(newChat);
  currentChatId.value = newChatId;

  messages.value = [
    {
      role: "assistant",
      content:
        "您好！我是您的AI农业助手。我可以为您提供农作物种植、病虫害防治、农产品管理等方面的建议。请问有什么我可以帮您的吗？",
      time: new Date(),
    },
  ];

  updateChatSession(messages.value[0]);
};

// 切换会话
const switchChat = async (chatId: string) => {
  currentChatId.value = chatId;
  loading.value = true;

  try {
    const res = await request({
      url: `/ai/history/${chatId}`,
      method: "get",
    });

    if (res.success && res.data) {
      // 处理消息内容，去掉前后的换行符
      messages.value = res.data.map((msg: ChatMessage) => ({
        ...msg,
        content: msg.content.trim(), // 使用 trim() 去掉前后的换行符和空格
      }));

      // 更新当前会话的最后一条消息预览
      const chatIndex = chatList.value.findIndex((c) => c.id === chatId);
      if (chatIndex > -1 && messages.value.length > 0) {
        const lastMessage = messages.value[0];
        chatList.value[chatIndex].lastMessage = lastMessage.content;
        chatList.value[chatIndex].updateTime = new Date();
      }
    }
  } catch (error) {
    console.error("获取历史消息失败:", error);
    ElMessage.error("获取历史消息失败");
    messages.value = [];
  } finally {
    loading.value = false;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 更新会话列表
const updateChatSession = (message: ChatMessage) => {
  const chatIndex = chatList.value.findIndex(
    (c) => c.id === currentChatId.value
  );
  if (chatIndex > -1) {
    const chat = chatList.value[chatIndex];
    chat.lastMessage = message.content;
    chat.updateTime = message.time || new Date();

    chatList.value.splice(chatIndex, 1);
    chatList.value.unshift(chat);
  }
};

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || loading.value || !currentChatId.value)
    return;

  const userMessage = inputMessage.value.trim();
  inputMessage.value = "";

  // 构造用户消息
  const newUserMessage: ChatMessage = {
    role: "user",
    content: userMessage,
  };

  // 添加到消息列表
  messages.value.push(newUserMessage);

  loading.value = true;
  try {
    const res = await request({
      url: "/user/rural/ai",
      method: "post",
      data: {
        message: userMessage,
        chatId: currentChatId.value,
      },
    });

    if (res.success) {
      // 添加AI响应消息，同时去掉前后的换行符
      const aiMessage: ChatMessage = {
        role: "assistant",
        content: res.data.trim(), // 使用 trim() 去掉前后的换行符和空格
      };
      messages.value.push(aiMessage);

      // 更新会话预览
      const chatIndex = chatList.value.findIndex(
        (c) => c.id === currentChatId.value
      );
      if (chatIndex > -1) {
        chatList.value[chatIndex].lastMessage = aiMessage.content;
        chatList.value[chatIndex].updateTime = new Date();
      }
    }
  } catch (error) {
    console.error("发送消息失败:", error);
    ElMessage.error("发送消息失败");
  } finally {
    loading.value = false;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 处理回车发送
const handleEnter = (e: KeyboardEvent) => {
  if (!e.shiftKey) {
    handleSend();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (!messagesRef.value) return;
  messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request({
      url: "/user/rural/queryInfo",
      method: "get",
    });
    if (res.success) {
      userAvatar.value = res.data.avatar;
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

onMounted(async () => {
  await getUserInfo();
  await fetchChatHistory();

  if (chatList.value.length === 0) {
    createNewChat();
  }
});
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 140px);
  background: #f5f7fa;
  padding: 20px;
  gap: 20px;
}

.chat-sidebar {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
    }
  }

  .chat-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;

    .chat-item {
      display: flex;
      align-items: center;
      padding: 12px;
      border-radius: 8px;
      cursor: pointer;
      margin-bottom: 4px;

      &:hover {
        background: #f5f7fa;
      }

      &.active {
        background: #ecf5ff;
      }

      .chat-info {
        flex: 1;
        margin: 0 12px;
        overflow: hidden;

        .chat-title {
          font-size: 14px;
          margin-bottom: 4px;
        }

        .chat-preview {
          font-size: 12px;
          color: #999;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .chat-time {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  margin-bottom: 20px;

  .message-content {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    max-width: 100%;
  }

  &.user .message-content {
    flex-direction: row-reverse;
  }

  .content {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
    max-width: 80%;
  }

  .text {
    background: #f4f4f5;
    padding: 12px 16px;
    border-radius: 8px;
    word-break: break-word;
    white-space: pre-wrap;
    font-size: 14px;
    line-height: 1.5;
  }

  &.user {
    .text {
      background: #e6f4ff;
    }

    .content {
      align-items: flex-end;
    }
  }

  .avatar {
    flex-shrink: 0;
  }

  .time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #dcdfe6;
  display: flex;
  gap: 16px;
  background: white;

  .el-textarea {
    flex: 1;
  }

  .el-button {
    align-self: flex-end;
    height: 78px;
    width: 80px;
  }
}

.typing-animation {
  display: flex;
  align-items: center;
  min-width: 60px;
  height: 35px;

  .dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #999;
    margin: 0 4px;
    animation: typing 1.4s infinite;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%,
  60%,
  100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-8px);
    opacity: 1;
  }
}

@keyframes message-fade-in {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 